package tt.dz.egobus.servicemanager.business.convert;

import org.springframework.core.convert.converter.Converter;
import tt.dz.egobus.servicemanager.business.key.BusinessCache;
import tt.dz.egobus.servicemanager.business.task.job.QuartzDynamicTask;
import tt.dz.egobus.servicemanager.core.task.DynamicTaskNamespace;

/**
 * @author Anson
 * @date 17-8-14
 * @name 命名空间转换器, 线程不安全
 * @since 1.0.6
 */
public class DynamicTaskNamespaceConvert implements Converter<BusinessCache, DynamicTaskNamespace> {

    /**
     * 前缀名转换器
     */
    private static final DynamicPreKeyConvert PRE_KEY_CONVERT = new DynamicPreKeyConvert();

    private Class<? extends QuartzDynamicTask> clazz;

    @Override
    public DynamicTaskNamespace convert(BusinessCache source) {
        if (this.clazz == null) {
            return null;
        }
        String groupJobName = this.getGroupJobName(source);
        String jobName = this.getJobName(source);
        String triggerName = this.getTriggerName(source);
        String triggerGroupName = this.getGroupTriggerName(source);
        DynamicTaskNamespace namespace = new DynamicTaskNamespace(
                jobName, groupJobName, triggerName, triggerGroupName);
        return namespace;
    }

    public String getGroupJobName(BusinessCache source) {
        return "GROUP_JOB_NAME" + "@" + this.getPreName();
    }

    public String getJobName(BusinessCache source) {
        return "JOB_NAME" + "@" + this.getPreName() + "#" + source.getBusinessId();
    }

    public String getGroupTriggerName(BusinessCache source) {
        return "TRIGGER_JOB_NAME" + "@" + this.getPreName();
    }

    public String getTriggerName(BusinessCache source) {
        return "TRIGGER_NAME" + "@" + this.getPreName() + "#" + source.getBusinessId();
    }

    public void setDynamicExecutorTask(Class<? extends QuartzDynamicTask> clazz) {
        this.clazz = clazz;
    }

    public String getPreName() {
        return PRE_KEY_CONVERT.convert(clazz);
    }
}
